#include "sysinfo_mgr.h"
#include <rtthread.h>
#include <dfs_posix.h>
#include <stdio.h>
#include <ulog.h>

#include "gw.h"
#include <ulog.h>
#include "cfg_struct2json.h"
#define GWJSON_MAX_LEN    128
extern gw_param g_gw_cfg;


rt_sem_t g_cfg_init_sem = NULL;
void async_sysinfo_init(void*param)
{
    gwinfo_load();
    //for test
   // gwinfo_save();
   LOG_D("place 3\n");
    //再次读取
  rt_sem_release(g_cfg_init_sem);
}

int sysinfo_mgr_init()
{
    g_cfg_init_sem = rt_sem_create("dsem", 0, RT_IPC_FLAG_PRIO);  
    rt_thread_t tid = rt_thread_create("sysinfo_mgr", async_sysinfo_init, RT_NULL, 8*2048, 20,10);
    if(tid != NULL )
    {
        rt_thread_startup(tid);
    }
    else{
        LOG_E("create sysinfo_mgr thread failed\n");
        rt_sem_delete(g_cfg_init_sem);
        return -1;
    }
    rt_sem_take(g_cfg_init_sem, RT_WAITING_FOREVER);
    LOG_D("finish sysinfo init\n");
    rt_sem_delete(g_cfg_init_sem);
}

int gwinfo_load()
{
    int fd = open(gwinfo_file, O_RDONLY|O_CREAT);
    if (fd < 0)
    {
        LOG_D("open %s failed\n",gwinfo_file);
        return -1;
    }
    uint8_t buf[GWJSON_MAX_LEN];
    rt_memset(buf, 0, GWJSON_MAX_LEN);
    lseek(fd, 0, SEEK_SET);
    int ret = read(fd, buf, GWJSON_MAX_LEN);
    if (ret <=0)
    {
        //default
        gw_param_init();
        LOG_E(" Read %s failed : read = %d",gwinfo_file, ret);
        close(fd);
        return -1;
    }
      LOG_D("place 9:%s\n",buf);
      cJSON* cjson = cJSON_Parse(buf);
      gw_param* s = json_to_struct_gw_param(cjson);
      cJSON_Delete(cjson);
    if(s!=NULL)
    {
        rt_memcpy(&g_gw_cfg,s,sizeof(gw_param));
    }
    else
    {
        //default
        gw_param_init();
        LOG_D("load sysinfo from flash Fail");
        close(fd);
        return -1;
    }
    LOG_D("load sysinfo from flash OK");
    close(fd);
    return 0;
}
int gwinfo_save()
{
    int fd = open(gwinfo_file, O_WRONLY);
    if (fd < 0)
    {
        LOG_D("open %s failed\n",gwinfo_file);
        return -1;
    }

    cJSON* j = struct_to_json_gw_param(&g_gw_cfg);
    if(j == NULL)
    {
        LOG_E(" change sysinfo.conf failed : ");
        close(fd);
        return -1;
    }
    char* p = cJSON_Print(j);
    LOG_D("%s\n",p);
    int ret = write(fd,p,rt_strlen(p));
    lseek(fd, 0, SEEK_SET);

    if (write(fd, p, rt_strlen(p)) != rt_strlen(p))
    {
        LOG_E(" Write to g_gw_cfg.json failed");
        cJSON_Delete(j);
        if(p) free(p);
        close(fd);
        return -1;
    }
    else
    {
        LOG_D(" Write to g_gw_cfg.json success");
    }
    cJSON_Delete(j);
    if(p) free(p);
    close(fd);
    LOG_D("save sysinfo to flash OK");
    return 0;
}